package com.iweb.commons.utils;

import com.alibaba.fastjson.JSON;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * @author: jack
 * @date: 2022-07-30 0030
 * @ApiNOTE:
 */
public class ModelAndView {

  private String viewName; // 视图路径
  private Map<String, Object> model = new HashMap<>();


  public void setViewName(String viewName) {
    this.viewName = viewName;
  }

  public String getViewName() {
    return viewName;
  }

  public void addModel(String key, Object value) {
    model.put(key, value);
  }

  public Map<String, Object> getModel() {
    return model;
  }

  public void render(HttpServletRequest req, HttpServletResponse resp, Object result) throws ServletException, IOException {

    // url 请求
    if (result instanceof ModelAndView) {
      ModelAndView mv = (ModelAndView) result;
      // 是否是重定向 redirect:/book/list
      if (mv.getViewName().startsWith("redirect:")) {
        String requestUrl = mv.getViewName().replace("redirect:", "");
        resp.sendRedirect(requestUrl);
        return;
      }

      // 保存数据
      if (mv.getModel().size() > 0) {
        // 遍历map  保存到 request 中
        Map<String, Object> model = mv.getModel();
        Set<Map.Entry<String, Object>> entries = model.entrySet();
        Iterator<Map.Entry<String, Object>> its = entries.iterator();
        while (its.hasNext()) {
          Map.Entry<String, Object> next = its.next();
          req.setAttribute(next.getKey(), next.getValue()); // 将 model 中的数据取出保存到 request
        }
      }
      // 渲染视图
      req.getRequestDispatcher(mv.getViewName()).forward(req, resp);
    } else {
      // ajax 请求
      String data = JSON.toJSONString(result);
      resp.setCharacterEncoding("utf-8");
      PrintWriter writer = resp.getWriter();
      writer.println(data);
      writer.flush();
      writer.close();
    }
  }

}
